# -*- coding: utf-8 -*-
# 从PyQt里面创建窗口和应用
import time
import sys
import inspect
import app.action as action
from app.util.FileUtil import MyFileUtil,MyXmlUtil
from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import Qt, QFile, QTranslator, Signal,QCoreApplication
from PySide2.QtXml import QDomDocument
from PySide2 import QtCore, QtGui, QtWidgets
import app.resources_rc
from system_hotkey import SystemHotkey
from app.view import DialogFactory

i18N = QCoreApplication.translate

class MyMainView(QMainWindow):
    action_dict = {}
    view_dict = {}
    # 初始化
    def __init__(self, parentContainer:QApplication):
        super(MyMainView,self).__init__()
        # 软件父类窗口
        self.__parentContainer = parentContainer
        trans = QTranslator()
        trans.load(":/qm/en_US")  # 没有后缀.qm
        self.__parentContainer.installTranslator(trans)
        self.__parentContainer.setWindowIcon(QIcon(':/image/logo'))
        # 加载action_dict
        self.init_action_dict()
        MyMainView.view_dict["myMainView"] = self;
        # 加载配置文件
        # 主题
        self.setStyleSheet(MyFileUtil.read2String(':/theme/1', QFile.ReadOnly, "utf-8", '\n'))
        # 配置
        self.appXmlDocDocument = MyXmlUtil.read2XmlDocDocument(':/config/app', QFile.ReadOnly)
        if self.appXmlDocDocument is None:
            # 抛异常或弹窗
            return
        # 设置主窗口的标题
        self.setWindowTitle("code-builder")
        # 设置初始化界面大小
        self.__viewSize()
        AppBuilder.createMenuBar(self)
        AppBuilder.createToolBar(self)
        AppBuilder.createCentralwidget(self)
        AppBuilder.createStatusbar(self)

        # 对于双击shift，双击ctrl的事件绑定
        self.key1_time = 0
        self.key1_modifiers = None

    def __viewSize(self):
        # 设置窗口的尺寸
        screen = self.__parentContainer.primaryScreen().geometry()
        defaultMainViewWidth = 800;
        defaultMAinViewHeight = 600;
        if(screen.width()>800 and screen.width()<=1920):
            defaultMainViewWidth = screen.width()
            defaultMAinViewHeight = screen.height()
        if(screen.width()>1920 and screen.width()<=3000):
            defaultMainViewWidth = 1920
            defaultMAinViewHeight = screen.height()
        self.resize(defaultMainViewWidth,defaultMAinViewHeight)
        self.showMaximized()

    #热键处理函数
    def MKey_pressEvent(self):
        # print("按下的按键是%s" % (i_str,))
        cw: QStackedWidget= self.centralwidget
        if cw.currentIndex()==1:
            cw.setCurrentIndex(0)
        else:
            cw.setCurrentIndex(1)

    def keyPressEvent(self,e:QtGui.QKeyEvent):
        # 比较
        currTime = time.time()
        diffTime = currTime-self.key1_time
        # print(diffTime)
        # 只有在初始化时self.key1_modifiers为None
        if self.key1_modifiers is not None:
            if diffTime<0.5:
                if e.modifiers() == Qt.ShiftModifier and self.key1_modifiers == Qt.ShiftModifier:
                    MyMainView.action_dict.get("shift_shift")()
                if e.modifiers() == Qt.ControlModifier and self.key1_modifiers == Qt.ControlModifier:
                    print('双击ctrl')
        # 记录
        self.key1_time = currTime
        self.key1_modifiers = e.modifiers()


    def keyReleaseEvent(self, e:QtGui.QKeyEvent) -> None:
        pass

    def init_action_dict(self):
        modules = inspect.getmembers(action, inspect.ismodule)
        for module in modules:
            funcs = inspect.getmembers(module[1], inspect.isfunction)
            for func in funcs:
                MyMainView.action_dict[func[0]]=func[1]

    def mousePressEvent(self, e:QMouseEvent):
        mainView:MyMainView = MyMainView.view_dict.get("myMainView")
        node = self.childAt(e.pos())
        if ~isinstance(node, DialogFactory.ShiftShiftDialog):
            if mainView.view_dict.__contains__("shift_shift_dialog"):
                dialog:DialogFactory.ShiftShiftDialog =mainView.view_dict.get("shift_shift_dialog")
                if ~dialog.isHidden():
                    dialog.hide()


class AppBuilder:

    @staticmethod
    def createMenuBar(myMainView: MyMainView):
        # """ createMenuBar(myMainView: MyMainView) -> None """
        menuBar = myMainView.menuBar()
        root = myMainView.appXmlDocDocument.documentElement()
        menubarEle = root.toElement().elementsByTagName('MenuBar').at(0).toElement()
        menuDirEle = menubarEle.elementsByTagName('MenuDir').at(0).toElement()
        menuDirEle_ChildNodes = menuDirEle.childNodes()
        for i in range(menuDirEle_ChildNodes.count()):
            menuI_ele = menuDirEle_ChildNodes.at(i).toElement()
            menuI_id_value = menuI_ele.attributeNode('id').value()
            menuI_ele_text = i18N('APP01', menuI_id_value)
            # print('--' + menuI_ele_text)
            mi = menuBar.addMenu(menuI_ele_text)
            mi.setMinimumWidth(400)
            mi.setObjectName(menuI_id_value)
            menuI_childNodes = menuI_ele.childNodes()
            for j in range(menuI_childNodes.count()):
                menuII_ele = menuI_childNodes.at(j).toElement()
                menuII_id_value = menuII_ele.attributeNode('id').value()
                menuII_ele_text = i18N('APP01', menuII_id_value)
                # print('----' + menuII_ele_text)
                if menuII_ele.hasAttribute('isLeaf') and menuII_ele.attributeNode('isLeaf').value() == 'Y':
                    action = mi.addAction(menuII_ele_text)
                    action.setObjectName(menuII_id_value)
                    if menuII_ele.hasAttribute('icon'):
                        action.setIcon(QIcon(menuII_ele.attributeNode('icon').value()))
                    if menuII_ele.hasAttribute('shortcut'):
                        action.setShortcut(menuII_ele.attributeNode('shortcut').value())

                    if MyMainView.action_dict.__contains__(menuII_id_value):
                        action.triggered.connect(MyMainView.action_dict[menuII_id_value])
                    else:
                        print('不存在'+menuII_id_value+'的绑定事件')
                else:
                    menuII_ele = menuI_childNodes.at(j).toElement()
                    menuII_childNodes = menuII_ele.childNodes()
                    mii = mi.addMenu(menuII_ele_text)
                    # action = mii.menuAction()
                    mii.setMinimumWidth(400)
                    for k in range(menuII_childNodes.count()):
                        menuIII_ele = menuII_childNodes.at(j).toElement()
                        menuIII_id_value = menuIII_ele.attributeNode('id').value()
                        menuIII_ele_text = i18N('APP01', menuIII_id_value)
                        # print('------' + menuIII_ele_text)
                        if menuIII_ele.hasAttribute('isLeaf') and menuIII_ele.attributeNode('isLeaf').value() == 'Y':
                            action = mii.addAction(menuIII_ele_text)
                            action.setObjectName(menuIII_id_value)
                            if menuII_ele.hasAttribute('icon'):
                                action.setIcon(QIcon(menuIII_ele.attributeNode('icon').value()))
                            if menuII_ele.hasAttribute('shortcut'):
                                action.setShortcut(menuIII_ele.attributeNode('shortcut').value())

                            if MyMainView.action_dict.__contains__(menuIII_id_value):
                                action.triggered.connect(MyMainView.action_dict[menuIII_id_value])
                            else:
                                print('不存在'+menuIII_id_value+'的绑定事件')

    @staticmethod
    def createToolBar(myMainView: MyMainView):
        tb1 = myMainView.addToolBar("File")
        toolbarWidget = QWidget()
        toolbarWidget.setFixedWidth(myMainView.geometry().width()-20)
        toolbarWidget.setMinimumHeight(40)
        tb1.addWidget(toolbarWidget)

        layout = QHBoxLayout(toolbarWidget);
        layout.setContentsMargins(0,0,0,0)

        toolbarrightWidget = QWidget()
        layoutright = QHBoxLayout(toolbarrightWidget);
        layoutright.setContentsMargins(0,0,0,0)

        layout.addWidget(toolbarrightWidget, 0, Qt.AlignRight|Qt.AlignVCenter)

        line = QWidget()
        line.setMinimumWidth(2)
        line.setFixedHeight(30)
        line.setStyleSheet("QWidget{background:black;margin-right:3px;margin-left:3px;}")
        layoutright.addWidget(line, 0, Qt.AlignRight|Qt.AlignVCenter)

        cb = QComboBox()
        # 用QComboBox里面的addItem添加
        cb.addItem(QIcon(":/image/logo"), 'C++')
        cb.addItem('Python')
        # 也可以直接添加多个
        cb.addItems(['Java','Go','C','C#'])
        layoutright.addWidget(cb, 0, Qt.AlignRight|Qt.AlignVCenter)
        # 在工具栏添加第二个按钮
        # tb1.actionTriggered.connect(lambda : toolbtnpressed(mainView, tb1))
        button = QToolButton()
        # QtCore.QRect(40, 60, 681, 181)
        button.setIcon(QIcon(":/image/run"))
        layoutright.addWidget(button, 0, Qt.AlignRight|Qt.AlignVCenter)

        button1 = QToolButton()
        button1.setIcon(QIcon(":/image/debug2"))
        layoutright.addWidget(button1, 0, Qt.AlignRight|Qt.AlignVCenter)

        button2 = QToolButton()
        button2.setIcon(QIcon(":/image/stop"))
        layoutright.addWidget(button2, 0, Qt.AlignRight|Qt.AlignVCenter)

        line1 = QWidget()
        line1.setMinimumWidth(2)
        line1.setFixedHeight(30)
        line1.setStyleSheet("QWidget{background:black;}")
        layoutright.addWidget(line1, 0, Qt.AlignRight|Qt.AlignVCenter)

        gitBtn = QToolButton()
        gitBtn.setIcon(QIcon(":/image/git"))
        layoutright.addWidget(gitBtn, 0, Qt.AlignRight|Qt.AlignVCenter)

        searchBtn = QToolButton()
        searchBtn.setIcon(QIcon(":/image/search"))
        layoutright.addWidget(searchBtn, 0, Qt.AlignRight|Qt.AlignVCenter)

        button4 = QToolButton()
        button4.setIcon(QIcon(":/image/settings"))
        layoutright.addWidget(button4, 0, Qt.AlignRight|Qt.AlignVCenter)

        button5 = QToolButton()
        button5.setIcon(QIcon(":/image/star-black"))
        layoutright.addWidget(button5, 0, Qt.AlignRight|Qt.AlignVCenter)

    @staticmethod
    def createStatusbar(myMainView: MyMainView):
        # 创建状态栏
        statusBar = QStatusBar()
        statusBar.setStyleSheet("QStatusBar{border-top:1px solid #014F84}")
        # 设置状态
        myMainView.setStatusBar(statusBar)

    @staticmethod
    def createCentralwidget(myMainView: MyMainView):
        #堆叠布局
        stackedWidget = QStackedWidget()
        w1 = QWidget()
        w1.setStyleSheet("QWidget{background:black;}")
        stackedWidget.insertWidget(0, w1)
        w2 = QWidget()
        w2.setStyleSheet("QWidget{background:red;}")
        stackedWidget.insertWidget(1, w2)
        stackedWidget.setCurrentIndex(0)
        myMainView.centralwidget = stackedWidget
        myMainView.centralwidget.setObjectName("centralwidget")
        myMainView.setCentralWidget(myMainView.centralwidget)


